package org.hshk.message.task;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.hshk.message.entity.CpMsgMember;
import org.hshk.message.entity.CpMsgMemberSign;
import org.hshk.message.entity.CpMsgPayDetail;
import org.hshk.message.entity.CpUnitBrand;
import org.hshk.message.mapper.CpMsgPayDetailMapper;
import org.hshk.message.mq.MQProducer;
import org.hshk.message.repository.*;
import org.hshk.message.utils.GthdMessageImpl;
import org.hshk.message.utils.HywxMessageImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.List;

/**
 * Created With IntelliJ IDEA
 * User: WangYong
 * Date: 2017/3/7 0007
 * Time: 10:48
 * ProjectName: msgCenterAPI
 * To change this template use File
 */
@Component
@RefreshScope
public class PollingOverageTask {
    //日志记录类
    private static final Logger log = LoggerFactory.getLogger(PollingOverageTask.class);
    //实例化线程操作对象
    private static final ThreadLocal<HttpClient> local = new ThreadLocal<HttpClient>();

    //线程操作对象获取
    private HttpClient getHttpClient() {
        if (null == local.get()) {
            HttpClient client = new HttpClient();
            local.set(client);
        }
        return local.get();
    }

    @Value("${message.notice.url}")
    private String rechargeUrl;
    @Value("${message.notice.brandId}")
    private int noticeBrandId;
    @Value("${message.notice.templateCode}")
    private String templateCode;


    @Autowired
    private MQProducer mqProducer;
    @Autowired
    private CpMsgMemberSignRepository cpMsgMemberSignRepository;
    //@Autowired
    //private CpMsgMemberSignService cpMsgMemberSignService;
    @Autowired
    private HywxMessageImpl hywxMessage;
    @Autowired
    private GthdMessageImpl gthdMessage;
    @Autowired
    CpMsgPayDetailRepository cpMsgPayDetailRepository;

    //@Autowired
    //private CpMsgMemberSignMapper cpMsgMemberSignMapper;

    //@Autowired
    //CpMsgTemplateRepository cpMsgTemplateRepository;

    //@Autowired
    //CpMsgMemberMapper cpMsgMemberMapper;

    @Autowired
    CpMsgMemberRepository cpMsgMemberRepository;
    @Autowired
    CpCpUnitBrandRepository cpCpUnitBrandRepository;
    @Autowired
    CpMsgPayDetailMapper cpMsgPayDetailMapper;

    @Scheduled(cron = "0 0/5 * * * ?")
//    @Scheduled(cron = "0/10 * * * * ?")
    public void pollingTask() {
        try {
            //获取is_user为yes的商家的所有信息
            List<CpMsgMemberSign> messageAccountList = cpMsgMemberSignRepository.findByIsUsed("Yes");
            Calendar calendar = Calendar.getInstance();
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);
            for (CpMsgMemberSign messageAccount : messageAccountList) {
                int balanceCount = 0;
                CpMsgMember cpMsgMember = cpMsgMemberRepository.findByOrgIdAndBrandId(messageAccount.getOrgId(), messageAccount.getBrandId());
                if (null == cpMsgMember) {
                    continue;
                }
                int totalCount = cpMsgMember.getTotalCount();
                if (0 == totalCount) {
                    continue;
                }
                //互亿无线
                if (messageAccount.getFactoryId() == 1) {
                    balanceCount = hywxMessage.overage(messageAccount.getBrandId(), messageAccount.getMsgUsername().trim(), messageAccount.getMsgPassword().trim());
                }
                //光通互动
                else if (messageAccount.getFactoryId() == 2) {

                    //List<CpMsgPayDetail> cpMsgPayDetails = cpMsgPayDetailMapper.findByUidAndBrandIdAndStatusAndFactoryId(cpMsgMember.getOrgId(), cpMsgMember.getBrandId(), "finished", 2);
                    /**
                     * Creat by yyl
                     * 2017年6月23日10:57:00
                     */
                    List<CpMsgPayDetail> cpMsgPayDetails =cpMsgPayDetailRepository.findByUidAndBrandIdAndStatusAndFactoryId(cpMsgMember.getOrgId(),cpMsgMember.getBrandId(),"finished",2);

                    if (null == cpMsgPayDetails || cpMsgPayDetails.size() == 0) {
                        continue;
                    }
                    int gthdConut = 0;
                    for (CpMsgPayDetail cpMsgPayDetail : cpMsgPayDetails) {
                        gthdConut = gthdConut + cpMsgPayDetail.getPayCount();
                    }
                    if (0 == gthdConut) {
                        continue;
                    }
                    int tmpBalance = gthdMessage.overage(messageAccount.getBrandId(), messageAccount.getMsgUsername().trim(), messageAccount.getMsgPassword().trim());
                    balanceCount = gthdConut - (1000000 - tmpBalance);
                }
                //条数更改和修改
                //cpMsgMemberMapper.upDateByBalanceCount(messageAccount.getOrgId(), messageAccount.getBrandId(), balanceCount);
                /**
                 * Creat by yyl
                 * 2017年6月23日08:43:55
                 */
                cpMsgMemberRepository.updateByorgIdAndbrandId(balanceCount, messageAccount.getOrgId(), messageAccount.getBrandId());

                if (balanceCount < 1000) {
                    if ((9 == hour || 21 == hour) && minute == 0) {
                        String[] alarmMobiles = cpMsgMember.getAlarmMobiles().split(",");
                        //3、变量替换
                        //根据品牌的id获取品牌名称
                        CpUnitBrand cpUnitBrand = cpCpUnitBrandRepository.findOne(messageAccount.getBrandId());
                        int msgBalanceCount = balanceCount < 0 ? 0 : balanceCount;
                        String[] variable = {cpUnitBrand.getBrandname(), String.valueOf(msgBalanceCount), rechargeUrl};
                        //判断报警联系人是否存在
                        if (alarmMobiles.length > 0) {
                            for (String alarm : alarmMobiles) {
                                JSONObject json = new JSONObject();
                                json.put("brandId", noticeBrandId);
                                json.put("mobile", alarm);
                                json.put("templateCode", templateCode);
                                json.put("parameters", variable);
                                //将消息放入队列，等待被消费
                                mqProducer.sendMessage(json);
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("PollingOverageTask [ 定时任务出错 : " + ex.getMessage() + " ]");
        }
    }
}